package cn.sdnu.database.controller;

import cn.sdnu.database.service.*;
import cn.sdnu.database.utils.SqlConvert;

import java.io.File;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 控制业务层与开始结合的类, 中间人
 * 
 * @author Master_Joe qiaoguangtong@aliyun.com
 */
public class DbController {

	public static final String HEADER_INFO = "helloworld";
	public static final String INTERVAL_INFO = "howareyouman";
	public static final String END_INFO = "fineThankyou";

	private static DbController dbController = null;
	private static ReentrantLock lock = new ReentrantLock();

	public static final String NULL_VALUE = "chengshizhiguang";

	/**
	 * 
	 */
	public static final String BASE = "Data" + File.separator;
	/**
	 * 测试数据库数据的路径
	 */
	public static final String TEST_BASE = "TestDatas" + File.separator;
	/**
	 * 表的后缀名
	 */
	public static final String EXTENSION = ".table";

	private DbController() {

	}

	public static DbController getInstance() {
		if (dbController == null) {
			lock.lock();
			try {
				if (dbController == null) {
					dbController = new DbController();
				}
			} finally {
				lock.unlock();
			}
		}
		return dbController;
	}

	/**
	 * handle sql we get from user input
	 *
	 * @param sql sql statement we will execute
	 */
	public void sqlHandle(String sql) {
		sql = SqlConvert.convert(sql);
		sql = sql.toLowerCase();
//		System.out.println(sql);

		if (sql.startsWith("select ")) {
			Select.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("create ")) {
			Create.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("delete ")) {
			Delete.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("drop ")) {
			Drop.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("insert into ")) {
			Insert.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("show ")) {
			Show.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("update ")) {
			Update.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("use ")) {
			Use.getInstance().sqlHandle(sql);
		} else if (sql.startsWith("desc")) {
			Describe.getInstance().sqlHandle(sql);
		} else if (sql.equals("exit;")) {
			System.out.println("Bye");
			System.exit(0);
		} else if (sql.contains("{") || sql.contains("}")) {
			System.out.println("You have some syntax error, please try again");
		} else {
			System.out.println("You have some syntax error, please try again");
		}
	}
}